'use client'

import { useState, useEffect } from 'react'
import { Product } from '@/types'
import { FormSelect } from '@/components/ui/form-select'

// 预定义的单位列表
const PRODUCT_UNITS = ['个', '件', '箱', 'kg', '包', '瓶', '盒', '套'] as const
type ProductUnit = typeof PRODUCT_UNITS[number]

// 预定义的单位选项
const UNIT_OPTIONS = [
  { value: '件', label: '件' },
  { value: '个', label: '个' },
  { value: '箱', label: '箱' },
  { value: 'kg', label: 'kg' },
  { value: '包', label: '包' },
  { value: '瓶', label: '瓶' },
  { value: '盒', label: '盒' },
  { value: '套', label: '套' },
] as const

type ProductUnit = (typeof UNIT_OPTIONS)[number]['value']

interface ProductFormProps {
  product: Product | null
  categories: { id: number; name: string }[]
  onClose: () => void
  onSave: (products: Product[]) => void
}

export const ProductForm: React.FC<ProductFormProps> = ({ 
  product, 
  categories, 
  onClose, 
  onSave 
}) => {
  const [name, setName] = useState('')
  const [code, setCode] = useState('')
  const [categoryId, setCategoryId] = useState<number>(categories[0]?.id || 0)
  const [unit, setUnit] = useState<ProductUnit>('件')
  const [price, setPrice] = useState('')
  const [stock, setStock] = useState('')
  const [description, setDescription] = useState('')

  useEffect(() => {
    if (product) {
      setName(product.name)
      setCode(product.code)
      setCategoryId(product.categoryId)
      setUnit(product.unit as ProductUnit)
      setPrice(product.price.toString())
      setStock(product.stock.toString())
      setDescription(product.description || '')
    } else {
      // 重置表单
      setName('')
      setCode('')
      setCategoryId(categories[0]?.id || 0)
      setUnit('件')
      setPrice('')
      setStock('')
      setDescription('')
    }
  }, [product, categories])

  useEffect(() => {
    console.log('Current unit:', unit)
    console.log('Available units:', UNIT_OPTIONS)
  }, [unit])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    const method = product ? 'PUT' : 'POST'
    const url = product ? `/api/products/${product.id}` : '/api/products'

    const response = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        name,
        code,
        categoryId,
        unit,
        price: parseFloat(price),
        stock: parseInt(stock),
        description,
      }),
    })

    if (response.ok) {
      // 获取最新的商品列表
      const updatedProducts = await fetch('/api/products').then(res => res.json())
      onSave(updatedProducts)
      onClose()
    }
  }

  return (
    <form onSubmit={handleSubmit} className="bg-white p-4 rounded shadow">
      <h2 className="text-lg font-semibold text-gray-800">{product ? '编辑商品' : '添加商品'}</h2>
      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="block text-gray-700">商品名称</label>
          <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            required
            className="border border-gray-300 p-2 w-full rounded"
          />
        </div>
        <div>
          <label className="block text-gray-700">商品编码</label>
          <input
            type="text"
            value={code}
            onChange={(e) => setCode(e.target.value)}
            required
            className="border border-gray-300 p-2 w-full rounded"
          />
        </div>
        <FormSelect
          label="分类"
          value={categoryId.toString()}
          onChange={(e) => setCategoryId(parseInt(e.target.value))}
          options={categories.map(cat => ({
            value: cat.id.toString(),
            label: cat.name
          }))}
          required
        />
        <FormSelect
          name="unit"
          label="单位"
          value={unit}
          onChange={(e) => setUnit(e.target.value as ProductUnit)}
          options={[...UNIT_OPTIONS]}
          required
        />
        <div>
          <label className="block text-gray-700">价格</label>
          <input
            type="number"
            step="0.01"
            value={price}
            onChange={(e) => setPrice(e.target.value)}
            required
            className="border border-gray-300 p-2 w-full rounded"
          />
        </div>
        <div>
          <label className="block text-gray-700">库存</label>
          <input
            type="number"
            value={stock}
            onChange={(e) => setStock(e.target.value)}
            required
            className="border border-gray-300 p-2 w-full rounded"
          />
        </div>
      </div>
      <div className="mt-4">
        <label className="block text-gray-700">描述</label>
        <textarea
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          className="border border-gray-300 p-2 w-full rounded"
          rows={3}
        />
      </div>
      <div className="mt-4 flex justify-end space-x-2">
        <button
          type="button"
          onClick={onClose}
          className="px-4 py-2 bg-gray-200 rounded hover:bg-gray-300"
        >
          取消
        </button>
        <button
          type="submit"
          className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
        >
          {product ? '更新' : '添加'}
        </button>
      </div>
    </form>
  )
} 